package com.wjr.braveheart.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public abstract class BaseFragment extends Fragment implements View.OnClickListener {

    private Context mContext;
    protected View mRootView = null;
    private SparseArray<View> mViews;
    /**
     * 上次点击时间
     */
    private long lastClick = 0;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    //Fragment在切换时，每次都会执行onCreateView(),导致rootView每次都会重绘，
    //使Fragment无法保持原有状态。
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (mRootView == null && bindLayoutId() > 0) {
            mRootView = inflater.inflate(bindLayoutId(), container, false);
        }
        //缓存的rootView需要判断是否已经被加过parent,如果有parent需要从parent删除,
        // 要不然会发生这个rootView已经有parent的错误。
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }
        return mRootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mViews = new SparseArray<>();
        initEventAndData(view, savedInstanceState, getArguments());
        loadData();
    }


    @Override
    public void onDestroyView() {
        if (mRootView != null) {
            ((ViewGroup) mRootView.getParent()).removeView(mRootView);
        }
        unbindView(mRootView);
        super.onDestroyView();
    }


    @Override
    public void onDestroy() {
        mRootView = null;
        super.onDestroy();
    }

    public Context getContext() {
        return mContext;
    }

    @Override
    public void onClick(final View view) {
        if (!isFastClick()) onWidgetClick(view);
    }


    /**
     * 绑定布局
     *
     * @return
     */
    protected abstract int bindLayoutId();

    /**
     * 初始化视图以及数据操作
     *
     * @param view               视图布局
     * @param savedInstanceState 保存实例状态
     * @param arguments          Intent的传值
     */
    protected abstract void initEventAndData(View view, Bundle savedInstanceState, Bundle arguments);

    /**
     * 加载数据
     */
    protected abstract void loadData();

    /**
     * 防止多次点击
     *
     * @param view
     */
    protected abstract void onWidgetClick(View view);

    /**
     * 解绑操作
     *
     * @param view
     */
    protected abstract void unbindView(View view);

    /**
     * 通过viewId获取控件
     *
     * @param id
     * @param <T>
     * @return
     */
    public <T extends View> T getView(@IdRes int id) {
        if (mRootView == null) {
            throw new NullPointerException("ContentView is null.");
        } else {
            T view = (T) mViews.get(id);
            if (view == null) {
                view = (T) mRootView.findViewById(id);
                mViews.put(id, view);
            }
            return view;
        }
    }

    /**
     * 通过viewId获取控件
     *
     * @param parentView 不能是局部变量(即不能是 View parentView = new View() )，
     *                   否则 getView() 获取mViews中缓存的控件无法和parentView关联，
     *                   导致后续数据绑定出现混乱
     * @param id
     * @param <T>
     * @return
     */
    public <T extends View> T getView(View parentView, @IdRes int id) {
        if (parentView == null) {
            throw new NullPointerException("parentView is null.");
        } else {
            T view = (T) mViews.get(id);
            if (view == null) {
                view = (T) parentView.findViewById(id);
                mViews.put(id, view);
            }
            return (T) parentView.findViewById(id);
        }
    }

    /**
     * 判断是否快速点击
     *
     * @return {@code true}: 是<br>{@code false}: 否
     */
    private boolean isFastClick() {
        long now = System.currentTimeMillis();
        if (now - lastClick >= 200) {
            lastClick = now;
            return false;
        }
        return true;
    }
}
